package com.sita.tboard.ui.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.sita.bike.R;
import com.sita.bike.persistence.RouteDao;
import com.sita.bike.persistence.RouteData;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.BitmapUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.ui.fragment.ComboPicLineChartFragment;
import com.sita.tboard.ui.fragment.ComboPicLineGreenChartFragment;
import com.sita.tboard.ui.fragment.LineChartFragment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class RoadRecordInformationDisplayActivity extends ActivityBase implements AMap.OnMarkerClickListener {
    private static final LatLng TIANJIN = new LatLng(39.08662, 117.203887);
    private static final CameraPosition CAMERA_POSITION_TIANJIN = new CameraPosition.Builder()
            .target(TIANJIN).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(30).build();
    public FragmentTransaction mFragmentTransaction;
    public FragmentManager mFragmentManager;
    public ComboPicLineChartFragment combine_fragment;
    public ComboPicLineGreenChartFragment green_combine_fragment;
    public LineChartFragment lineChartFragment;
    public MapView mMapView;
    public AMap aMap;
    public Marker myMarker;
    private long trackID;
    float maxSpeed = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information_display);
        mMapView = (MapView) findViewById(R.id.roadmate_map);
        mMapView.onCreate(savedInstanceState);
        initMap();
        Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        trackID = bundle.getLong("trackID");
        final String avespeed = bundle.getString("avespeed");
        displayTrack(trackID);

        final ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
            //设置组视图的显示文字
            private String[] province = new String[]{"速度计数表", "转速计数表", "油耗计数表"};

            public View getchildView() {
                View view = LayoutInflater.from(RoadRecordInformationDisplayActivity.this).
                        inflate(R.layout.expandablelistviewchild_item, null);
                return view;
            }

            //重写ExpandableListAdapter中的各个方法
            @Override
            public int getGroupCount() {
                return province.length;
            }

            @Override
            public Object getGroup(int groupPosition) {
                return province[groupPosition];
            }

            @Override
            public long getGroupId(int groupPosition) {
                return groupPosition;
            }

            @Override
            public int getChildrenCount(int groupPosition) {
                return 1;
            }

            @Override
            public Object getChild(int groupPosition, int childPosition) {
                return 1;
            }

            @Override
            public long getChildId(int groupPosition, int childPosition) {
                return childPosition;
            }

            @Override
            public boolean hasStableIds() {
                return true;
            }

            @Override
            public View getGroupView(int groupPosition, boolean isExpanded,
                                     View convertView, ViewGroup parent) {
                convertView = LayoutInflater.from(RoadRecordInformationDisplayActivity.this).
                        inflate(R.layout.exceplse_list_item, null);
                TextView textView = (TextView) convertView.findViewById(R.id.tv_record_title);
                TextView tv_title1 = (TextView) convertView.findViewById(R.id.tv__record_title1);
                TextView tv_title2 = (TextView) convertView.findViewById(R.id.tv__record_title2);
                TextView tv_title3 = (TextView) convertView.findViewById(R.id.tv__record_title3);
                ImageView image_chose_state = (ImageView) convertView.findViewById(R.id.image_direction);
                if (isExpanded) {
                    image_chose_state.setImageResource(R.drawable.direction_down);
                } else {
                    image_chose_state.setImageResource(R.drawable.direction);
                }
                if (groupPosition == 2) {
                    image_chose_state.setVisibility(View.GONE);
                }
                switch (groupPosition) {
                    case 0:
                        textView.setText(getGroup(groupPosition).toString());
                        tv_title1.setText("最高时速:" + formatSpeed(maxSpeed * 3600) + "km/h");
                        tv_title2.setText("平均时速:" + avespeed);
                        tv_title3.setVisibility(View.GONE);
                        break;
                    case 1:
                        textView.setText(getGroup(groupPosition).toString());
                        tv_title1.setText("最高转速:6000rpm");
                        tv_title2.setText("平均转速:3942rpm");
                        tv_title3.setVisibility(View.GONE);
                        break;
                    case 2:
                        textView.setText(getGroup(groupPosition).toString());
                        tv_title1.setText("全程总耗油量：35L");
                        tv_title2.setText("当前油价：5.5     ");
                        tv_title3.setText("全程总耗油量：192.5L");
                        break;
                }

                return convertView;
            }

            @Override
            public View getChildView(int groupPosition, int childPosition,
                                     boolean isLastChild, View convertView, ViewGroup parent) {
                switch (groupPosition) {
                    case 0:
                        combine_fragment = ComboPicLineChartFragment.newInstance(trackID);
                        mFragmentManager = getFragmentManager();
                        mFragmentTransaction = mFragmentManager.beginTransaction();
                        mFragmentTransaction.add(R.id.containers, combine_fragment).commit();
                        break;
                    case 1:
                        green_combine_fragment = new ComboPicLineGreenChartFragment();
                        mFragmentManager = getFragmentManager();
                        mFragmentTransaction = mFragmentManager.beginTransaction();
                        mFragmentTransaction.add(R.id.containers, green_combine_fragment).commit();
                        break;
                }
                View view = getchildView();
                return view;
            }

            @Override
            public boolean isChildSelectable(int groupPosition, int childPosition) {
                return true;
            }

        };
        final ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.expandable_listview);
        expandableListView.setAdapter(adapter);

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < 3; i++) {
                    if (groupPosition != i) {
                        expandableListView.collapseGroup(i);
                    }
                }
            }
        });
        //设置item点击的监听器
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Toast.makeText(
                        RoadRecordInformationDisplayActivity.this,
                        adapter.getChild(groupPosition, childPosition).toString(),
                        Toast.LENGTH_SHORT).show();

                return false;
            }
        });
    }

    private String formatSpeed(float distance) {
        float distance_km = distance / 1000;
        String distance_result = "0";
        DecimalFormat decimalFormat;
        if (distance_km < 10) {
            decimalFormat = new DecimalFormat("0.00");
            distance_result = decimalFormat.format(distance_km);
        } else if (distance >= 10 && distance < 100) {
            decimalFormat = new DecimalFormat("0.0");
            distance_result = decimalFormat.format(distance_km);
        } else if (distance >= 100) {
            decimalFormat = new DecimalFormat("0");
            distance_result = decimalFormat.format(distance_km);
        }
        return distance_result;
    }

    public void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            setMapUi();
        }
        setTraffic();

        aMap.setOnMarkerClickListener(this);

        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        drawMyMarker(latLng);

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(30).build();

        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    private void displayTrack(long trackId) {
        List<RouteData> gps = PersistUtils.getRouteDataList(trackId);
        final List<LatLng> locs = new ArrayList<>();

        for (RouteData g : gps) {
            locs.add(new LatLng(Double.valueOf(g.getLatitude()), Double.valueOf(g.getLongitude())));
            if (maxSpeed < g.getSpeed()) {
                maxSpeed = g.getSpeed();
            }
        }
        aMap.clear();
        if (locs.size() != 0) {
            LatLng startlatlng = locs.get(0);
            LatLng endlatlng = locs.get(locs.size() - 1);
            drawSrartEndMaker(startlatlng, endlatlng);
        }
        aMap.addPolyline(new PolylineOptions().width(10).color(Color.RED).addAll(locs));
        aMap.setOnMapLoadedListener(new OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                moveBound(locs);
            }
        });


    }

    private void moveBound(List<LatLng> locs) {
        if (!locs.isEmpty()) {
            LatLngBounds bounds = aMap.getProjection().getVisibleRegion().latLngBounds;
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
//            if (myMarker != null) {
//                builder.include(myMarker.getPosition());
//            }
            boolean changeBounds = false;
//            if (!bounds.contains(myMarker.getPosition())) {
//                changeBounds = true;
//            }
            for (LatLng latLng : locs) {
                if (!bounds.contains(latLng)) {
                    builder.include(latLng);
                    changeBounds = true;
                }
            }
            if (changeBounds) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 0));
                float zoomLevel = aMap.getCameraPosition().zoom - 1;
                aMap.moveCamera(CameraUpdateFactory.zoomTo(zoomLevel));
            }
        } else {
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(myMarker.getPosition()).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(aMap.getCameraPosition().bearing).tilt(aMap.getCameraPosition().tilt).build();
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
        }

    }

    @Override
    public void onPause() {
        if (mMapView != null) {
            mMapView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onDestroy() {
        if (mMapView != null) {
            mMapView.onDestroy();
        }
        super.onDestroy();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {

        return false;
    }

    private void setMapUi() {
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);

        CameraUpdate update = CameraUpdateFactory.newCameraPosition(CAMERA_POSITION_TIANJIN);
        aMap.moveCamera(update);
    }

    private void setTraffic() {
        MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
        myTrafficStyle.setSeriousCongestedColor(0xff92000a);
        myTrafficStyle.setCongestedColor(0xffea0312);
        myTrafficStyle.setSlowColor(0xffff7508);
        myTrafficStyle.setSmoothColor(0xff00a209);
        aMap.setTrafficEnabled(false);
    }

    private void drawMyMarker(LatLng latLng) {
        if (myMarker != null && !myMarker.isVisible()) {
            myMarker.destroy();
            myMarker = null;
        }

        if (myMarker == null) {
            Bitmap locationMe= BitmapUtils.zoomBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.location_me), 100, 100);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(locationMe);
            myMarker = aMap.addMarker(new MarkerOptions().draggable(false).icon(icon).position(latLng));
        } else {
            myMarker.setPosition(latLng);
        }

    }

    private void drawSrartEndMaker(LatLng startlatLng, LatLng endLatlng) {
        BitmapDescriptor icona = BitmapDescriptorFactory.fromResource(R.drawable.location_a);
        BitmapDescriptor iconb = BitmapDescriptorFactory.fromResource(R.drawable.location_b);
        aMap.addMarker(new MarkerOptions().draggable(false).icon(icona).position(startlatLng));
        aMap.addMarker(new MarkerOptions().draggable(false).icon(iconb).position(endLatlng));
    }

    public void notifyLocation(AMapLocation location) {
        if (myMarker != null) {
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            drawMyMarker(latLng);
        }
    }

    public void turnDown(Activity activity) {
        Intent intent = new Intent(RoadRecordInformationDisplayActivity.this, activity.getClass());
        startActivity(intent);
    }
}


